package fr.lgm.client;
import java.util.ArrayList;
import java.util.List;

import fr.lgm.shared.FieldVerifier;
import fr.lgm.shared.Members;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalSplitPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.ProvidesKey;
import fr.lgm.client.MyDialog;


/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
@SuppressWarnings("deprecation")
public class Lgm implements EntryPoint {
	
	final CellTable<User> table = new CellTable<User>(KEY_PROVIDER);
	  private static class User {
		  	private static int nextId = 0;

		    private final int id;
		    private String name;
		    private final String first_name;
		    private String activity;

		    public User(String name, String first_name, String activity) {
		      nextId++;
		      this.id = nextId;
		      this.name = name;
		      this.first_name = first_name;
		      this.activity = activity;
		      
		    }
		  }
	  
	  
	private List<User> USERS; 
			 
	String []days;
	
	private static final ProvidesKey<User> KEY_PROVIDER = new ProvidesKey<Lgm.User>() {
		   public Object getKey(User item) {
		     return item.id;
		   }
		 };
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final ScheduleRequestAsync greetingService = GWT
			.create(ScheduleRequest.class);
	
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		
		
		days=new String[15];
		//days[0]="zero";days[1]="one";days[2]="two";
		
		
		
		final HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
		splitPanel.setSize("729px", "900px");
		splitPanel.setSplitPosition("30%");
		
		
		final Label pwd = new Label("Password :");
		final Button sendButton = new Button("Launch schedule");
		final PasswordTextBox nameField = new PasswordTextBox();
		nameField.setText("password");
		final Label errorLabel = new Label();
		
		/**
		 * Tree 
		 */	
		
		TreeItem tree = new TreeItem("Schedule legend");
		tree.addItem("Tigre (Activite)");
		tree.addItem("42C (Activite");
		tree.addItem("CA (Conges annuel)");
		tree.addItem("JTL (Journee temps libre)");
		tree.addItem("TP (Temps partiel)");
		tree.addItem("MAL (Arret maladie)");
		tree.addItem("DP (?)");
		tree.addItem("DS (?)");
		tree.addItem("GRE (Greve)");
		tree.addItem("CHSCT (Comite d'hygiene...)");
		tree.addItem("ASA (?)");
		tree.addItem("FOR (Formation)");
	    	
	    Tree t = new Tree();
	    t.addItem(tree);
	    /**
	     * End Tree
	     */
	    
	    Label dbtext = new Label();
	    dbtext.setText("Add an User/Activity :");
	    HTML space = new HTML();
	    space.setHTML("<br />");
	    Button pButton = new Button("+");
	    pButton.addStyleName("AdminButon");
	    Label dbtext2 = new Label();
	    dbtext2.setText("Remove an User/Activity :");
	    Button rButton = new Button("-");
	    rButton.addStyleName("AdminButton");
	    
    
	    /**
	     * StackPanel
	     */
	    final VerticalPanel sPanel = new VerticalPanel();
	    sPanel.setWidth("200px");
	    sPanel.add(dbtext);	    
	    sPanel.add(pButton);
	    sPanel.add(space);
	    sPanel.add(dbtext2);
	    sPanel.add(rButton);

	       
	    DecoratedStackPanel panel = new DecoratedStackPanel();
	    panel.setWidth("218px");
	    panel.add(sPanel,"Administration");
	    panel.add(t,"Schedule legend");
	    panel.add(new Label("coming..."),"Doc. staff");	
	    panel.add(new Label(""),"Activity");
	    /**
	     * End StackPanel
	     */

	    splitPanel.setLeftWidget(panel);
	    splitPanel.setRightWidget(nameField);
	    splitPanel.setRightWidget(sendButton);
	    splitPanel.setRightWidget(errorLabel);
	    
	    Image image = new Image("lgm/gwt/standard/images/logo-orange.jpg");
	    
		RootPanel.get("pwd").add(pwd);
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);
		RootPanel.get().add(splitPanel);
		RootPanel.get("image").add(image);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();
	
		/**
		 * pop up schedule
		 */
		       
		USERS=new ArrayList<Lgm.User>();
		greetingService.getUser(new AsyncCallback<Members[]>() {
			
	
			@Override
			public void onSuccess(Members[] result) {
						
				for(int i=0; i< result.length;i++)
					USERS.add(new User(result[i].firstname,result[i].lastname,result[i].activity));
				
				
				
				//user provider
			    ListDataProvider<User> dataProvider = new ListDataProvider<User>();
			    dataProvider.addDataDisplay(table);
			    
			    List<User> list = dataProvider.getList();
			    for (User contact : USERS) {
			      list.add(contact);
			    }						
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub				
			}
		}
		);
		
   
	    table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);    	    
	    TextColumn<User> nameColumn = new TextColumn<User>() {
	        @Override
	        public String getValue(User user) {
	          return user.name;
	        }
	      };    
	    TextColumn<User> lastnameColumn = new TextColumn<User>() {
	        @Override
	        public String getValue(User user) {
	          return user.first_name;
	        }
	      };	 
		 final EditTextCell nameCell3 = new EditTextCell();
		 final   Column<User, String> activityColumn = new Column<User, String>(nameCell3) {
		     @Override
		     public String getValue(User object) {
		       return object.activity;
		     }
		   };
	      	      
         
	    table.addColumn(nameColumn, "Last name");
	    table.addColumn(lastnameColumn, "First name");
	    
	  
	    
	    
	 // Add a field updater to be notified when the user enters a new name.
	    activityColumn.setFieldUpdater(new FieldUpdater<User, String>() {
	      public void update(int index, User object, String value) {
	        // Validate the data.
	        if (value.length() < 3) {
	          Window.alert("Incorrect value.");

	          /*
	           * Clear the view data. The view data contains the pending change and
	           * allows the table to render with the pending value until the data is
	           * committed. If the data is committed into the object, the view data
	           * is automatically cleared out. If the data is not committed because
	           * it is invalid, you must delete.
	           */
	          nameCell3.clearViewData(KEY_PROVIDER.getKey(object));

	          // Redraw the table.
	          table.redraw();
	          return;
	        }

	        // Inform the user of the change.
	        Window.alert("You changed the activity " + object.activity + " to " + value);

	        // Push the changes into the Contact. At this point, you could send an
	        // asynchronous request to the server to update the database.
	        object.activity = value;

	        // Redraw the table with the new data.
	        table.redraw();
	      }
	    });
	    
	    /**
	     * 
	     */	
		
		final Button closeButton = new Button("Close");
		closeButton.getElement().setId("closeButton");
		
		final Button closeButtonA = new Button("Close");
		closeButtonA.getElement().setId("closeButtonA");
		
		final Button sendButtonA = new Button("Send");
		sendButtonA.getElement().setId("sendButtonA");
		
		final Button sendButton2 = new Button("Send");
		sendButton2.getElement().setId("sendButton2");
		
		final Image Imember = new Image("lgm/gwt/standard/images/member.jpg");
		final Image ImemberR = new Image("lgm/gwt/standard/images/activity.png");
		
		final Label tLabelL = new Label("Add a member :");		
		final Label tLabelR = new Label("Add an activity :");
		
		final Image Imember2 = new Image("lgm/gwt/standard/images/member.jpg");
		final Image ImemberR2 = new Image("lgm/gwt/standard/images/activity.png");
		
		final Label tLabelL2 = new Label("Remove a member :");		
		final Label tLabelR2 = new Label("Remove an activity :");
		
		final Label textToServerLabel = new Label();
		
		final TextBox lastname = new TextBox();
		final TextBox firstname = new TextBox();
		final TextBox mainactivity = new TextBox();
		
		final TextBox nom = new TextBox();
		final TextBox legende = new TextBox();		
		final TextBox comments = new TextBox();
		
		final HTML serverResponseLabel = new HTML();
		
		/**
		 * DialogBox Schedule
		 */		
		final MyDialogS mydialog2 = new MyDialogS();
		mydialog2.setText("Schedule");
		mydialog2.setAnimationEnabled(true);
		
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		mydialog2.setWidget(dialogVPanel);
		dialogVPanel.add(table);				
		/**
		 * 
		 */
		
		/**
		 * DialogBox Administration (add User + Activity)
		 */	
		final HorizontalSplitPanel aPanel = new HorizontalSplitPanel();
		aPanel.setSize("600px", "180px");
		aPanel.setSplitPosition("50%");
		
		final MyDialog mydialog = new MyDialog();
		AbsolutePanel adminPanel = new AbsolutePanel();
		mydialog.setWidget(aPanel);
		adminPanel.addStyleName("adminPanel");
		adminPanel.setPixelSize(200, 180);
		adminPanel.insert(Imember, 20, 5, 0);
		adminPanel.insert(tLabelL, 50, 7, 0);
		adminPanel.insert(lastname, 20, 35, 0);
		adminPanel.insert(firstname, 20, 80, 0);
		adminPanel.insert(mainactivity, 20, 125, 0);
			
		lastname.setText("Last Name");
		firstname.setText("First Name");
		mainactivity.setText("Main Activity");
		
		AbsolutePanel adminPanelR = new AbsolutePanel();
		mydialog.setWidget(aPanel);
		adminPanelR.addStyleName("adminPanel");
		adminPanelR.setPixelSize(200, 180);
		adminPanelR.insert(ImemberR, 20, 5, 0);
		adminPanelR.insert(tLabelR, 50, 7, 0);
		adminPanelR.insert(nom, 20, 35, 0);
		adminPanelR.insert(legende, 20, 80, 0);
		adminPanelR.insert(comments, 20, 125, 0);
		//adminPanelR.add(sendButtonA);	

		nom.setText("Name");
		legende.setText("Legend");
		comments.setText("Comments");
		
		aPanel.setLeftWidget(adminPanel);
		aPanel.setRightWidget(adminPanelR);
		/**
		 * 
		 */
		
		/**
		 * DialogBox Administration (remove User/Activity)
		 */
		final Label tLabel1 = new Label();
		tLabel1.setText("Remove a member :");
		
		final Label tLabel2 = new Label();
		tLabel2.setText("Remove an activity :");
		
		final TextBox lastname2 = new TextBox();
		final TextBox firstname2 = new TextBox();
		final TextBox mainactivity2 = new TextBox();
		
		final TextBox nom2 = new TextBox();
		final TextBox legende2 = new TextBox();		
		final TextBox comments2 = new TextBox();
		
		final HorizontalSplitPanel aPanel2 = new HorizontalSplitPanel();
		aPanel2.setSize("600px", "180px");
		aPanel2.setSplitPosition("50%");
		
		final MyDialog mydialogR = new MyDialog();
		AbsolutePanel adminPanel2 = new AbsolutePanel();
		mydialogR.setWidget(aPanel2);
		adminPanel2.addStyleName("adminPanel");
		adminPanel2.setPixelSize(200, 180);
		adminPanel2.insert(Imember2, 20, 5, 0);
		adminPanel2.insert(tLabelL2, 50, 7, 0);
		adminPanel2.insert(lastname2, 20, 35, 0);
		adminPanel2.insert(firstname2, 20, 80, 0);
		adminPanel2.insert(mainactivity2, 20, 125, 0);		
		
		lastname2.setText("Last Name");
		firstname2.setText("First Name");
		mainactivity2.setText("Main Activity");
	
		
		AbsolutePanel adminPanelR2 = new AbsolutePanel();
		mydialogR.setWidget(aPanel2);
		adminPanelR2.addStyleName("adminPanel");
		adminPanelR2.setPixelSize(200, 180);
		adminPanelR2.insert(ImemberR2, 20, 5, 0);
		adminPanelR2.insert(tLabelR2, 50, 7, 0);
		adminPanelR2.insert(nom2, 20, 35, 0);
		adminPanelR2.insert(legende2, 20, 80, 0);
		adminPanelR2.insert(comments2, 20, 125, 0);
		
		nom2.setText("Name");
		legende2.setText("Legend");
		comments2.setText("Comments");
	
		
		aPanel2.setLeftWidget(adminPanel2);
		aPanel2.setRightWidget(adminPanelR2);
		
		
		//administration button, pop up launcher (add)
		pButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				//adminBox.show();
				mydialog.center();
				mydialog.show();			
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});
		
		//administration button, pop up launcher (remove)
		rButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				mydialogR.center();
				mydialogR.show();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});
		
		
		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				greetingService.getCurrentMonth(new AsyncCallback<String[]>() {
					
					@Override
					public void onSuccess(String[] res) {
						// TODO Auto-generated method stub
						table.redraw();
						days = res;
						int i = 0;
						
						    while (i<15){				    
						    table.addColumn(activityColumn, days[i]);
						    i++;
						    }											
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});
						
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}
			
			

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendNameToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				String textToServer = nameField.getText();
				if (!FieldVerifier.isValidName(textToServer)) {
					errorLabel.setText("Wrong password.");
					return;
				}

				// Then, we send the input to the server.
				sendButton.setEnabled(true);
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								mydialog2.setText("Remote Procedure Call - Failure");
								serverResponseLabel.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								mydialog2.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {								
								mydialog2.setText("Schedule - GRBL Application");
								serverResponseLabel.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								mydialog2.center();
								closeButton.setFocus(true);
							}
							
							
						});				
			}			
		}
		
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);			
		
		
	}
}
